import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import {
  setPageNavBar,
  useLocation,
  useNavigate,
  useSearchParams,
} from 'alita';
import {
  Button,
  Card,
  CascaderView,
  DatePicker,
  Divider,
  DotLoading,
  Form,
  Image,
  Input,
  NavBar,
  Radio,
  Result,
  Space,
  Switch,
  TextArea,
  Toast,
} from 'antd-mobile';
import { RefObject, useEffect, useState } from 'react';

import { DATE_FOMRAT } from '@/constants';
import {
  getRequestInit,
  obsPrifix,
  postRequestInit,
  urlPrefix,
} from '@/utils/http';
import { useModel } from 'alita';
import { AntOutline, RightOutline } from 'antd-mobile-icons';
import { DatePickerRef } from 'antd-mobile/es/components/date-picker';
import dayjs from 'dayjs';
import styles from './index.less';
const numberFormator = new Intl.NumberFormat();

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  
  const [haveOASystem, setHaveOASystem] = useState<boolean>(false);

  const [departmentTree, setDepartmentTree] = useState<
    {
      value: string;
      label: string;
    }[]
  >([]);

  type FieldModal = {
    items: number[];
    itemInvoiceSupplementComplete?: boolean;
  };
  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `初始化系统`,
        pageBackground: '#eee',
      },
    });

    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 1;
      // 加载所有微信部门
      fetch(
        `${urlPrefix}/api/rayplatform/department/get-department-tree`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                ({
                  data,
                  code,
                  msg,
                }: DetailResult<{ value: string; label: string }[]>) => {
                  if (code === 0) {
                    if (data) {
                      setDepartmentTree(data!);
                    }
                    setLoadOK(msg);
                  } else {
                    setLoadFails([...loadFails, msg]);
                  }
                },
              )
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载报销科目：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
      
        

      // 检查是否有OASystem
      fetch(
        `${urlPrefix}/api/oa-system-handle/have-oa-system`,
        getRequestInit(),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<boolean>) => {
                if (code === 0) {
                  if (data) {
                    setHaveOASystem(data!);
                  }
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载报销科目：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK]);

  

  const onFinish = (values: FieldModal) => {
    // Dialog.alert({
    //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // });
    // return;
    const url = '/api/oa-system-handle/create-oa-system';
    const requestInit: RequestInit = postRequestInit(values);
    let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<number>) => {
              const { code, msg } = x;
              if (code === 0) {
                setSuccess(msg);
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
              console.error(`${url} catch in 最内层!`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}[${url}]`);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setIng(false);
        console.log(`finally in 最外层:${url}`);
      });
  };

  

  const [uing, setUing] = useState<boolean>(false);
  const initWeiXinUser = () => {
    setUing(true);
    const url = '/api/rayplatform/wei-xin-user/init-wei-xin-user';
    const requestInit: RequestInit = postRequestInit({ tree: departmentTree });
    let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<string[]>) => {
              const { code, msg } = x;
              if (code === 0) {
                Toast.show({ icon: 'success', content: msg });
              } else {
                Toast.show({
                  icon: 'fail',
                  content: msg,
                });
              }
            })
            .catch((reason) => {
              console.error(`${url} catch in 最内层!${reason}`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setUing(false);
        console.log(`finally in 最外层:${url}`);
      });
  }; // end initWeiXinUser

  const [initDepartmentIng, setDnitDepartmentIng] = useState<boolean>(false);

  function initOADepartment() {
    console.log('正在从钉钉中初始化部门');
    setDnitDepartmentIng(true);
    const typeOptionsUrl = `/api/rayplatform/department/get-all-simplelist`; // 生成代码搜索位置：2492-0412-5263-8850-4512-8512-3502
    fetch(`${urlPrefix}${typeOptionsUrl}`, getRequestInit())
      .then(async (rsp: Response) => {
        // fetch返回类型： Promise<Response>
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ code, msg }: DetailResult<any>) => {
              if (code === 0) {
                Toast.show({ content: msg });
              } else {
                Toast.show({ content: msg });
              }
            })
            .catch((reason) => {
              console.log(reason);
            })
            .finally(() => {
              console.log(`${typeOptionsUrl} inner finally!`);
            });
        }
      })
      .catch((reason: any) => {
        console.error(reason);
      })
      .finally(() => {
        console.log(`${typeOptionsUrl} outter finally!`);
        setDnitDepartmentIng(false);
      });
  }



  

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            初始化系统
          </NavBar>
        </DemoBlock>

        <Card
          title={
            <div style={{ fontWeight: 'normal' }}>
              <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
              上传excelx,等非pdf,jpg文件是，缩略图是否正确地返回,注意检查是否配置好自定义域名:{obsPrifix}
            </div>
          }
          extra={<RightOutline />}
          // onBodyClick={onBodyClick}
          // onHeaderClick={onHeaderClick}
          style={{ borderRadius: '16px', margin: '10px' }}
        >
          <div className={styles.content}>
            <Space direction={'vertical'}>
              <Image
                src={`${obsPrifix}/thumb/file.jpg`}
                width={64}
                height={64}
                fit="cover"
                style={{ borderRadius: 4 }}
              />
              <Image
                src={`${obsPrifix}/thumb/xlsx.jpg`}
                width={64}
                height={64}
                fit="cover"
                style={{ borderRadius: 4 }}
              />
              <Image
                src={`${obsPrifix}/thumb/docx.jpg`}
                width={64}
                height={64}
                fit="cover"
                style={{ borderRadius: 4 }}
              />
            </Space>
          </div>
          <div className={styles.footer} onClick={(e) => e.stopPropagation()}>
            <Button
              color="primary"
              disabled
              onClick={() => {
                Toast.show('点击了底部按钮');
              }}
            >
              abc
            </Button>
          </div>
        </Card>

        <Card
          title={
            <div style={{ fontWeight: 'normal' }}>
              <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
              企业微信后一级部门
            </div>
          }
          extra={<RightOutline />}
          // onBodyClick={onBodyClick}
          // onHeaderClick={onHeaderClick}
          style={{ borderRadius: '16px', margin: '10px' }}
        >
          <div className={styles.content}>
            <CascaderView
              options={departmentTree}
              style={{ '--height': '320px' }}
            />
          </div>

          <div className={styles.footer} onClick={(e) => e.stopPropagation()}>
            <Space direction={'horizontal'}>
              <Button
                color="primary"
                loading={uing}
                disabled={uing || departmentTree.length < 1}
                onClick={initWeiXinUser}
              >
                初始化用户
              </Button>
              <Button
                color="primary"
                loading={initDepartmentIng}
                disabled={initDepartmentIng || departmentTree.length < 1}
                onClick={initOADepartment}
              >
                初始化一级部门
              </Button>
            </Space>
          </div>
        </Card>


        {!haveOASystem && (
          <Card
            title={
              <div style={{ fontWeight: 'normal' }}>
                <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
                创建OASystem
              </div>
            }
            extra={<RightOutline />}
            // onBodyClick={onBodyClick}
            // onHeaderClick={onHeaderClick}
            style={{ borderRadius: '16px', margin: '10px' }}
          >
            <div className={styles.content}>
              <Form
                form={form}
                layout={'vertical'}
                onFinish={onFinish}
                footer={
                  <>
                    {success !== undefined && (
                      <Result
                        status="success"
                        title="成功初始化"
                        description={
                          <Space>
                            <Button
                              size={'small'}
                              type={'button'}
                              color="primary"
                              onClick={() => navigate(-1)}
                            >
                              返回
                            </Button>
                          </Space>
                        }
                      />
                    )}
                    {fail !== undefined && (
                      <Result
                        status="error"
                        title="执行失败"
                        description={
                          <Space direction="vertical">
                            {fail}
                            <Divider aria-orientation={'vertical'} />
                            <Button
                              color="default"
                              size="small"
                              onClick={() => setFail(undefined)}
                            >
                              再试一次
                            </Button>
                          </Space>
                        }
                      />
                    )}
                    <Button
                      block
                      type="submit"
                      disabled={
                        !authOK ||
                        ing ||
                        fail !== undefined ||
                        success !== undefined
                      }
                      loading={ing}
                      color="primary"
                      size="large"
                    >
                      {success !== undefined ? '已申请' : '提交'}
                    </Button>
                  </>
                }
              >
                <Form.Item
                  name="name"
                  label={'名称'}
                  rules={[{ required: true, message: '名称' }]}
                >
                  <Input maxLength={200} />
                </Form.Item>

                <Form.Item name="maxLiveDevive" label="最大设备在线数">
                  <Input maxLength={10} />
                </Form.Item>
                </Form>
              
            </div>
            <div className={styles.footer} onClick={(e) => e.stopPropagation()}>
              {/* <Button
                color="primary"
                disabled
                onClick={() => {
                  Toast.show('点击了底部按钮');
                }}
              >
                abcd
              </Button> */}
            </div>
          </Card>
        )}
      </Content>
    </Page>
  );
};
